#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import os
from logging.handlers import RotatingFileHandler
from config import config

def setup_logger(name: str = 'p2p_vpn') -> logging.Logger:
    """配置并返回日志记录器"""
    # 创建日志记录器
    logger = logging.getLogger(name)
    
    # 设置日志级别
    log_level = getattr(logging, config.get('log_level', 'INFO'))
    logger.setLevel(log_level)
    
    # 创建格式化器
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    # 创建文件处理器
    log_file = config.get('log_file', 'p2p_vpn.log')
    file_handler = RotatingFileHandler(
        log_file,
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5
    )
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    
    return logger

# 全局日志记录器实例
logger = setup_logger()